library(stringr)
library(Pmetrics)
wd <- c("E:/document/demo")
setwd(wd)
setwd("runs")

data <- "2501b.csv"
model2 <- "3C_1Cov.txt"
model <- "3C_1.txt"

file.copy(from=c(str_c("../", model), str_c("../", data)),to=getwd(),overwrite=T)
NPrun(data=data ,model=model)

getwd()
PMload(1)
plot(mdata.1)
plot(mdata.1,overlay=F,xlim=c(120,144))
plot(op.1,pred.type="pop",resid=T,y.stat=1,x.stat=0,cex.stat=0.8)
plot(cov.1,V~wt,icen="mean")

# EXERCISE 2 - NPAG WITH COVARIATES ---------------------------------------
setwd(paste(wd,"/runs",sep=""))
file.copy(from=c(str_c("../", data),str_c("../", model2)),to=getwd(),overwrite=T)

NPrun(data=data, model=model2)
PMload(2)

# EXERCISE 3 - COMPARING MODELS -------------------------------------------
PMcompare(1,2)
PMcompare(1,2,plot=T,cex.stat=0.5)

# EXERCISE 4 - MODEL VALIDATION -------------------------------------------
setwd(paste(wd,"/runs",sep=""))
npde.2 <- makeNPDE(run=2,limits=NA)
str(npde.2)
npde.2[[1]]@results@res
plot(npde.2)
plot(npde.2,plot.type="vpc",ylog=F)
npc.2 <- plot(sim.2,obs=op.2,log=F)
npc.2$npc

# EXERCISE 5 - SIMULATOR RUN ----------------------------------------------
setwd(paste(wd,"/sim",sep=""))
file.copy(from=c(str_c("../", model2),str_c("../", data)),to=getwd(),overwrite=T)
SIMrun(poppar=final.2,data=data,model=model2,limits=NA,nsim=1000,doseNoise = c(0.01,0.01,0.015,0.02))
plot(simdata)
simdata <- SIMparse("simout?.txt")
plot(simdata[[3]])
simdata2 <- SIMparse("simout?.txt",combine=T)
plot(simdata2)

covariate <- list(cov=cov.2,
                  mean=list(wt=50),
                  sd=list(wt=20),
                  limits=list(wt=c(10,70)),
                  fix=c("WT","ASIA","AGE","GENDER","HEIGHT","Ccr","ALB","APACHEII"))
SIMrun(poppar=final.2,data="run0103a.csv",model="3C_1Cov.txt",include=1:4,limits=NA,nsim=1000,
       covariate=covariate)

simdata3 <- SIMparse("simout?.txt")

plot(simdata[[1]])
plot(simdata3[[1]])

simdata3[[1]]$parValues

# EXERCISE 6 - SAVING PMETRICS OBJECTS ------------------------------------
setwd(paste(wd,"/Runs",sep=""))
PMsave(2)
PMsave(2,simdata)
PMload(2)


# EXERCISE 7 - CONTINUING RUNS OR EXTERNAL VALIDATIONS --------------------
setwd(paste(wd,"/Runs",sep=""))

NPrun(data=2,model=2,prior=2)
PMload(3)


# EXERCISE 8 - EXAMPLE PARAMETRIC IT2B --------------------------------
setwd(paste(wd,"/Runs",sep=""))

file.copy(from=c("../3C_1.txt","../run.csv"),to=getwd(),overwrite=T)

ITrun(data="run.csv",model="3C_1.txt")
PMload(4)

plot(final.4)
plot(final.4,standard=T)
plot(final.4,Ke~V0)


# EXERCISE 9 - makePTA --------------------------------
makePTA(simdata3,  c("Regimen 1", "Regimen 2"), c(0.25, 0.5,1,2,4,8), "auc", 0.9, outeq = 1,
        free.fraction = 1, 0, 12)